package com.example.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.example.common.annotations.Log;
import com.example.common.enums.BusinessType;
import com.example.domain.User;
import com.example.service.UserService;
import com.example.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/doLogin")
    @ApiOperation("用户登录接口")
    @Log(title = "用户登录", businessType = BusinessType.L0GIN)
    public R doLogin(@RequestBody User user) {
        String token = userService.login(user);
        //获取 Token  相关参数
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        // 第3步，返回给前端
        return R.success(tokenInfo);
    }

    @GetMapping("/info")
    @ApiOperation("获取登录用户信息")
    @SaCheckRole("admin")
    public R getInfo() {
        User user = userService.getById(StpUtil.getLoginIdAsLong());
        return R.success(user);
    }

    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    public R register(@RequestBody User user) {
        userService.register(user);
        return R.success();
    }

    /*
     * 用户退出
     * */
    @GetMapping("/logout")
    @ApiOperation("退出登录")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

    /*
     * 账号封禁
     * */
    @GetMapping("/disable/{userId}")
    @ApiOperation("账号封禁")
    public R disable(@PathVariable Long userId) {
        userService.disable(userId);
        return R.success();
    }

    /*
     * 强制注销
     * */
    @GetMapping("/forceLogout/{userId}")
    @ApiOperation("强制注销")
    public R forceLogout(@PathVariable Long userId) {
        userService.logout(userId);
        return R.success();
    }

    /*
     * 踢人下线
     * */
    @GetMapping("/kickout/{userId}")
    @ApiOperation("踢人下线")
    public R kickout(@PathVariable Long userId) {
        userService.kickout(userId);
        return R.success();
    }

    /*
     * 获取在线用户
     * */
    @GetMapping("/online")
    @ApiOperation("获取在线用户")
    public R online() {
        List<User> list = userService.onlineUsers();
        return R.success(list);
    }

}
